import session from 'express-session'
import express from 'express'
import path from 'path'

import permissionRouter from './router/PermissionRouter.js'
import RoleRouter from './router/RoleRouter.js'
import UserRouter from './router/UserRouter.js'
import AdminUser from './router/admin/AdminUser.js'
import CategoryRouter from './router/CategoryRouter.js'
import ArticleRouter from './router/ArticleRouter.js'
import MinArticleRouter from './router/MinArticleRouter.js'
import FileRouter from './router/FileRouter.js'

import RBAC from './util/RBAC.js'

let app = express()

//静态文件服务器
app.use(express.static(path.join(path.resolve(), '/public')))
//解析application/json
app.use(express.json())
//解析application/x-www-form-urlencoded
app.use(express.urlencoded())

//设置session
app.set('trust proxy', 1) // trust first proxy
app.use(session({
    secret: 'server-session',
    name: 'sessionToCookieName',
    resave: false,
    saveUninitialized: true,
    rolling: true,
    cookie: { 
        maxAge: 3 * 60 * 60 * 1000,
    }
}))

//权限
app.use(RBAC)

//文件处理
app.use((req, res, next) => {
    //保存临时头像图url
    if (!req.session.head_imgs) req.session.head_imgs = []
     //保存临时微头条封面图url
    if (!req.session.min_article_files) req.session.min_article_files = []
    //保存临时文章封面图url
    if (!req.session.cover_imgs) req.session.cover_imgs = []
    //保存临时文章内容图url
    if (!req.session.article_imgs) req.session.article_imgs = []
    //保存临时文章内容视频url
    if (!req.session.article_videos) req.session.article_videos = []

    next()
})
app.use(FileRouter)

//正式路由
app.use(permissionRouter)
app.use(RoleRouter)
app.use(UserRouter)
app.use(AdminUser)
app.use(CategoryRouter)
app.use(ArticleRouter)
app.use(MinArticleRouter)

app.listen(3000, () => {
    console.log('app is running at http://127.0.0.1:3000')
})